package com.codepilot.server.filter;

import java.io.IOException;

import javax.security.sasl.AuthenticationException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import com.codepilot.server.model.dto.UserDTO;
import com.codepilot.server.utils.JwtUtil;
import com.codepilot.server.utils.RedisCache;

/**
 * 自定义Jwt认证过滤器
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String token = request.getHeader("Authorization");

        // 若请求头中不含token，则直接放行
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 检验token合法性
        if (!jwtUtil.validateToken(token)) {
            throw new AuthenticationException("token非法");
        }

        // 解析token，获取用户信息
        String username = jwtUtil.getUsernameFromToken(token);

        // 从redis中获取loginUser
        UserDTO loginUser = redisCache.getCacheObject("login:" + username);

        // 将用户和权限信息封装进Authentication中，存入SecurityContextHolder
        // UsernamePasswordAuthenticationToken authenticationToken = new
        // UsernamePasswordAuthenticationToken(
        // loginUser.getUsername(),
        // loginUser.getPassword(),
        // loginUser.getAuthorities());
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,
                null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 放行
        filterChain.doFilter(request, response);
    }

}
